#ifndef CHRONOMETER_H
#define CHRONOMETER_H

#include <ctime>

struct chronometer
{
  clock_t t1;
  clock_t t2;
  clock_t interval;
  clock_t max_interval;
  double mean_interval;
  int deadline_ms;
  long unsigned cycles;
  long unsigned overrun;

  chronometer(int deadline_ms)
    : t1(0), t2(0), interval(0), max_interval(), mean_interval(0), deadline_ms(deadline_ms), cycles(0), overrun(0)
  {}

  void start()
  {
    t1 = clock();
  }

  void stop()
  {
    t2 = clock();
    interval = t2-t1;
    if(interval>max_interval)
      max_interval=interval;
    mean_interval *= static_cast<double>(cycles)/(static_cast<double>(cycles+1));
    mean_interval += static_cast<double>(interval)/static_cast<double>(++cycles);
    if(ms() > deadline_ms)
      ++overrun;
  }

  clock_t ms()
  {
    return interval*1000/CLOCKS_PER_SEC;
  }

  double mean_ms()
  {
    return mean_interval*1000/CLOCKS_PER_SEC;
  }
};

#endif
